package leetcode.题库.链表;

/**
 * 删除链表的倒数第 N 个结点
 *
 * @author yanzhenming
 * @date 2023/3/23  16:50
 */

/**
 * 描述
 *
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点
 */

import leetcode.题库.pubclass.ListNode;

/**
 * 思路
 *
 * 双指针
 */
public class Solution9 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode sentry = new ListNode();
        sentry.next = head;
        ListNode tmp = sentry;
        int count = 0;
        while (head != null) {
            head = head.next;
            if (count >= n) {
                tmp = tmp.next;
            }
            count++;
        }
        tmp.next = tmp.next.next;
        return sentry.next;
    }
}

